
package com.the9tcat.deliverycoming;

import java.util.Date;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.feedback.UMFeedbackService;
import com.mobclick.android.MobclickAgent;
import com.the9tcat.deliverycoming.data.Configure;

/**
 * The Class SettingActivity.
 * 
 * @author jpwl88@gmail.com
 */
public class SettingActivity extends Activity {

    /** CheckBox 启用LED. */
    CheckBox ledCheck;

    /** CheckBox 启用声音. */
    CheckBox soundCheck;

    /** CheckBox 启用振动. */
    CheckBox vebrateCheck;

    /** TextView 更新周期副标题. */
    TextView updateInfoText;

    /** TextView 铃声类型副标题. */
    TextView soundInfoText;
    
    /** TextView 广告位置副标题. */
    TextView adPostionInfoText;

    /** TextView 免打扰副标题. */
    TextView dndInfoText;

    /** The m configure. */
    Configure mConfigure;

    /** The m ringtone. */
    Ringtone mRingtone;

    /** The m ringtont manager. */
    RingtoneManager mRingtontManager;
    
    Toast toast;

    /** 更新周期数组索引. */
    int updateFreqIndex;
    
    /** 广告位置索引. */
    int adPostionIndex;

    /** 铃声类型索引. */
    int soundIndex;

    /** 最小免打扰起始时间</br>默认18. */
    private final int DND_START_TIME_MIN = 18;

    /** 最小免打扰终止时间</br>默认7. */
    private final int DND_END_TIME_MIN = 7;

    /** The update srt array. */
    String[] updateSrtArray;
    /** The ad's postion */
    String[] adpostionArray;

    /** The sound type array. */
    String[] soundTypeArray;

    private AlarmManager mAlarm;

    /*
     * (non-Javadoc)
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        toast = Toast.makeText(this, R.string.change_ad_position, Toast.LENGTH_SHORT);
        setContentView(R.layout.setting);
        ((ImageView) findViewById(R.id.dnd_more_img))
                .setImageResource(android.R.drawable.ic_menu_more);
        ((ImageView) findViewById(R.id.update_fre_img))
                .setImageResource(android.R.drawable.ic_menu_more);
        ((ImageView) findViewById(R.id.sound_type_img))
                .setImageResource(android.R.drawable.ic_menu_more);
        ((ImageView) findViewById(R.id.adposition_img))
        .setImageResource(android.R.drawable.ic_menu_more);
        registerControls();
    }

    /**
     * 初始化各组件的值.
     */
    private void initSetting() {
        ledCheck.setChecked(mConfigure.isLedEnabled());
        soundCheck.setChecked(mConfigure.isSoundEnabled());
        vebrateCheck.setChecked(mConfigure.isVebrateEnabled());
        updateInfoText.setText(updateSrtArray[mConfigure.getUpdateFreqIndex()]);
        soundInfoText.setText(soundTypeArray[mConfigure.getSoundIndex() + 1]);
        adPostionInfoText.setText(adpostionArray[mConfigure.getAdPositionIndex()]);
        if (mConfigure.isDndEnabled()) {
            String dndEndable = getResources()
                    .getString(R.string.setting_dnd_enable_text);
            dndInfoText.setText(dndEndable + mConfigure.getDndStart()
                    + ":00 - " + mConfigure.getDndEnd() + ":00");
        } else {
            dndInfoText.setText(R.string.setting_dnd_disable_text);
        }
    }

    /**
     * Register controls.
     */
    public void registerControls() {
        mConfigure = Configure.getInstance(this);
        mRingtontManager = new RingtoneManager(this);

        updateSrtArray = getResources()
                .getStringArray(R.array.setting_update_freq_array);
        adpostionArray = getResources()
        .getStringArray(R.array.setting_adposition_array);
        soundTypeArray = getSoundTypeArray();

        ledCheck = (CheckBox) findViewById(R.id.setting_led_check);
        soundCheck = (CheckBox) findViewById(R.id.setting_sound_check);
        vebrateCheck = (CheckBox) findViewById(R.id.setting_vebrate_check);

        soundInfoText = (TextView) findViewById(R.id.setting_sound_type_info);
        adPostionInfoText = (TextView) findViewById(R.id.setting_adposition_info);
        dndInfoText = (TextView) findViewById(R.id.setting_dnd_info);
        updateInfoText = (TextView) findViewById(R.id.setting_update_freq_info);

        initSetting();

        OnClickListener listener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                case R.id.setting_feedback:
                	UMFeedbackService.openUmengFeedbackSDK(SettingActivity.this);
                    break;
                case R.id.setting_about_us:
                    // 关于我们
                    Intent intent = new Intent();
                    intent.setClass(SettingActivity.this, AboutActivity.class);
                    startActivity(intent);
                    break;
                case R.id.setting_dnd_time:
                    // 免打扰时间
                    dndTimeDialog();
                    break;
                case R.id.setting_update_freq:
                    // 更新周期
                    updateFreqDialog();
                    break;
                case R.id.setting_noti_led:
                    // LED提示
                    ledCheck.setChecked(!ledCheck.isChecked());
                    mConfigure.enableLed(ledCheck.isChecked());
                    break;
                case R.id.setting_noti_sound:
                    // 铃声提示
                    soundCheck.setChecked(!soundCheck.isChecked());
                    mConfigure.enableSound(soundCheck.isChecked());
                    break;
                case R.id.setting_noti_vebrate:
                    // 铃声提示
                    vebrateCheck.setChecked(!vebrateCheck.isChecked());
                    mConfigure.enableVebrate(vebrateCheck.isChecked());
                    break;
                case R.id.setting_sound_type:
                    // 设置铃声
                    soundTypeDialog();
                    break;
                case R.id.setting_adposition:
                	//广告位置
                	updateAdPositionDialog();
                	break;
            }
        }
        };
        findViewById(R.id.setting_about_us).setOnClickListener(listener);
        findViewById(R.id.setting_dnd_time).setOnClickListener(listener);
        findViewById(R.id.setting_update_freq).setOnClickListener(listener);
        findViewById(R.id.setting_noti_sound).setOnClickListener(listener);
        findViewById(R.id.setting_noti_led).setOnClickListener(listener);
        findViewById(R.id.setting_noti_vebrate).setOnClickListener(listener);
        findViewById(R.id.setting_sound_type).setOnClickListener(listener);
        findViewById(R.id.setting_feedback).setOnClickListener(listener);
        findViewById(R.id.setting_adposition).setOnClickListener(listener);
    }

    /**
     * 显示免打扰设置对话框
     */
    private void dndTimeDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.setting_dnd_time);
        LinearLayout ll = (LinearLayout) LayoutInflater.from(this)
                .inflate(R.layout.setting_dnd, null);
        final CheckBox dndCheckBox = (CheckBox) ll
                .findViewById(R.id.setting_dnd_check);
        final TextView startText = (TextView) ll
                .findViewById(R.id.setting_start_time);
        final TextView endText = (TextView) ll
                .findViewById(R.id.setting_end_time);
        final SeekBar startSeek = (SeekBar) ll
                .findViewById(R.id.dnd_start_seek);
        final SeekBar endSeek = (SeekBar) ll.findViewById(R.id.dnd_end_seek);
        startSeek.setProgress(mConfigure.getDndStart() - 18);
        endSeek.setProgress(mConfigure.getDndEnd() - 7);
        dndCheckBox.setChecked(mConfigure.isDndEnabled());
        final String startStr = getResources()
                .getString(R.string.setting_dnd_start_time);
        final String endStr = getResources()
                .getString(R.string.setting_dnd_end_time);
        startText.setText(startStr
                + (startSeek.getProgress() + DND_START_TIME_MIN) + ":00");
        endText.setText(endStr + (endSeek.getProgress() + DND_END_TIME_MIN)
                + ":00");

        boolean isDndEnabled = dndCheckBox.isChecked();
        startSeek.setEnabled(isDndEnabled);
        startText.setEnabled(isDndEnabled);
        endSeek.setEnabled(isDndEnabled);
        endText.setEnabled(isDndEnabled);

        dndCheckBox
                .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton arg0,
                            boolean arg1) {
                        boolean isDndEnabled = dndCheckBox.isChecked();
                        startSeek.setEnabled(isDndEnabled);
                        startText.setEnabled(isDndEnabled);
                        endSeek.setEnabled(isDndEnabled);
                        endText.setEnabled(isDndEnabled);
                    }
                });
        startSeek
                .setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                    }

                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {
                    }

                    @Override
                    public void onProgressChanged(SeekBar seekBar,
                            int progress, boolean fromUser) {
                        startText.setText(startStr
                                + (progress + DND_START_TIME_MIN) + ":00");
                    }
                });
        endSeek
                .setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                    }

                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {
                    }

                    @Override
                    public void onProgressChanged(SeekBar seekBar,
                            int progress, boolean fromUser) {
                        endText.setText(endStr + (progress + DND_END_TIME_MIN)
                                + ":00");
                    }
                });
        builder.setPositiveButton(R.string.setting_button_ok,
                                  new DialogInterface.OnClickListener() {

                                      @Override
                                      public void onClick(DialogInterface arg0,
                                              int arg1) {
                                          mConfigure.enableDnd(dndCheckBox
                                                  .isChecked());
                                          mConfigure.setDndStart(startSeek
                                                  .getProgress()
                                                  + DND_START_TIME_MIN);
                                          mConfigure.setDndEnd(endSeek
                                                  .getProgress()
                                                  + DND_END_TIME_MIN);

                                          if (mConfigure.isDndEnabled()) {
                                              startMsgService();
                                          }
                                          initSetting();
                                      }
                                  });
        builder.setNegativeButton(R.string.setting_button_cancel, null);
        builder.setView(ll);
        builder.create().show();
    }

    /**
     * 显示更新周期对话框
     */
    private void updateFreqDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.setting_update_freq);

        int index = mConfigure.getUpdateFreqIndex();

        builder.setSingleChoiceItems(R.array.setting_update_freq_array, index,
                                     new DialogInterface.OnClickListener() {
                                         @Override
                                         public void onClick(
                                                 DialogInterface dialog,
                                                 int which) {
                                             updateFreqIndex = which;
                                         }
                                     });
        builder.setPositiveButton(R.string.setting_button_ok,
                                   new DialogInterface.OnClickListener() {
                                       @Override
                                       public void onClick(
                                               DialogInterface arg0, int arg1) {
                                           mConfigure
                                                   .setUpdateFreq(updateFreqIndex);
                                           initSetting();
                                       }
                                   });
        builder.setNegativeButton(R.string.setting_button_cancel, null);
        builder.create().show();
    }
    
    /**
     * 显示更新周期对话框
     */
    private void updateAdPositionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.setting_adposition);

        int index = mConfigure.getAdPositionIndex();

        builder.setSingleChoiceItems(R.array.setting_adposition_array, index,
                                     new DialogInterface.OnClickListener() {
                                         @Override
                                         public void onClick(
                                                 DialogInterface dialog,
                                                 int which) {
                                        	 adPostionIndex = which;
                                         }
                                     });
        builder.setPositiveButton(R.string.setting_button_ok,
                                   new DialogInterface.OnClickListener() {
                                       @Override
                                       public void onClick(
                                               DialogInterface arg0, int arg1) {
                                           mConfigure
                                                   .setAdPosition(adPostionIndex);
                                           toast.show();
                                           initSetting();
                                       }
                                   });
        builder.setNegativeButton(R.string.setting_button_cancel, null);
        builder.create().show();
    }

    /**
     * Gets the sound type array.
     * 
     * @return the sound type array
     */
    private String[] getSoundTypeArray() {
        mRingtontManager.setType(RingtoneManager.TYPE_ALARM
                | RingtoneManager.TYPE_NOTIFICATION);
        Cursor cur = mRingtontManager.getCursor();
        final String[] str = new String[cur.getCount() + 1];
        str[0] = getResources().getString(R.string.setting_default_sound);
        int i = 1;
        if (cur.moveToFirst()) {
            do {
                str[i] = cur.getString(RingtoneManager.TITLE_COLUMN_INDEX);
                i++;
            } while (cur.moveToNext());
        }
        cur.close();
        return str;
    }

    /**
     * Sound type dialog.
     */
    private void soundTypeDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.setting_sound_type);

        int index = mConfigure.getSoundIndex() + 1;
        // 如果用户删了铃声，则这儿要处理
        if (index > soundTypeArray.length - 1) {
            index = 0;
        }

        builder.setSingleChoiceItems(soundTypeArray, index,
                                     new DialogInterface.OnClickListener() {
                                         @Override
                                         public void onClick(
                                                 DialogInterface dialog,
                                                 int which) {
                                             soundIndex = which - 1;
                                             // 预览铃声
                                             if (mRingtone != null
                                                     && mRingtone.isPlaying()) {
                                                 mRingtone.stop();
                                             }
                                             if (soundIndex == -1) {
                                                 mRingtone = RingtoneManager
                                                         .getRingtone(
                                                                      SettingActivity.this,
                                                                      RingtoneManager
                                                                              .getDefaultUri(RingtoneManager.TYPE_ALARM
                                                                                      | RingtoneManager.TYPE_NOTIFICATION));
                                             } else {
                                                 mRingtone = mRingtontManager
                                                         .getRingtone(soundIndex);
                                             }
                                             mRingtone.play();
                                         }
                                     });

        builder.setPositiveButton(R.string.setting_button_ok,
                                  new DialogInterface.OnClickListener() {
                                      @Override
                                      public void onClick(
                                              DialogInterface dialog, int which) {
                                          mConfigure.setSound(soundIndex);
                                          if (mRingtone != null
                                                  && mRingtone.isPlaying()) {
                                              mRingtone.stop();
                                              mRingtone = null;
                                          }
                                          initSetting();
                                      }
                                  });
        builder.setNegativeButton(R.string.setting_button_cancel,
                                  new DialogInterface.OnClickListener() {
                                      @Override
                                      public void onClick(
                                              DialogInterface dialog, int which) {
                                          // 取消设置铃声
                                          if (mRingtone != null
                                                  && mRingtone.isPlaying()) {
                                              mRingtone.stop();
                                              mRingtone = null;
                                          }
                                      }
                                  });
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface arg0) {
                // 取消设置铃声
                if (mRingtone != null && mRingtone.isPlaying()) {
                    mRingtone.stop();
                    mRingtone = null;
                }
            }
        });
        builder.create().show();
    }

    private void startMsgService() {
        mAlarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        PendingIntent startIntent = PendingIntent
                .getBroadcast(this, 0, new Intent(AlarmReceiver.START_ALARM), 0);

        PendingIntent cancleIntent = PendingIntent
                .getBroadcast(this, 0, new Intent(AlarmReceiver.CANCLE_ALARM),
                        0);

        Date date = new Date();

        mAlarm.set(AlarmManager.RTC_WAKEUP, date.getTime()
                    , cancleIntent);
        if (date.getHours() >= mConfigure.getDndStart()
                    && date.getHours() < mConfigure.getDndEnd()) {
            mAlarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
                           startIntent);
        }
        date.setHours(0);
        date.setMinutes(0);
        date.setSeconds(0);
        mAlarm.setRepeating(AlarmManager.RTC_WAKEUP, date.getTime()
                    + mConfigure.getDndStart() * 60 * 60 * 1000,
                                (24 * 60 * 60 * 1000), startIntent);
        mAlarm.setRepeating(AlarmManager.RTC_WAKEUP, date.getTime()
                    + mConfigure.getDndEnd() * 60 * 60 * 1000,
                                (24 * 60 * 60 * 1000), cancleIntent);

    }
    
    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }


	@Override
    protected void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(this);
    }
}
